import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import { PluginLocal, PluginLocalTool } from '@shared/types/entity'
export type PluginLocalItem = PluginLocal & {
  tools: PluginLocalTool[]
}

interface PluginLocalStoreTool {
  data: PluginLocalTool[]
  initData: () => Promise<void>
  form: {
    type: 'add' | 'edit' | 'debug'
    data?: PluginLocalTool
    plugin?: PluginLocal
  }
  debugForm: (data: PluginLocalTool, plugin: PluginLocal) => void
  editForm: (data: PluginLocalTool, plugin: PluginLocal) => void
  addForm: (mark: string) => void
}

const usePluginLocalToolStore = create<PluginLocalStoreTool>()(
  immer(
    (set): PluginLocalStoreTool => ({
      data: [],
      initData: async () => {
        const data = await window.api.pluginLocalTool.getList({})
        set((state) => {
          state.data = data
        })
      },
      form: { type: 'add' },
      debugForm: (data, plugin) =>
        set((state) => {
          state.form.type = 'debug'
          state.form.data = data
          state.form.plugin = plugin
        }),
      editForm: (data, plugin) =>
        set((state) => {
          state.form.type = 'edit'
          state.form.data = data
          state.form.plugin = plugin
        }),
      addForm: (mark) =>
        set((state) => {
          state.form.type = 'add'
          state.form.data = {
            mark: '',
            name: '',
            pluginMark: mark,
            description: '',
            inputSchema: [],
            outputSchema: ''
          }
        })
    })
  )
)

export default usePluginLocalToolStore
